package utils;

import common.JsonResult;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Iterator;
import java.util.Map;

/**
 * @author bill
 * @date 2023/2/14 15:02
 */
public class RestTemplateUtil {

    private static RestTemplate restTemplate = new RestTemplate();

    public  static JsonResult getWithParam(String url, Map params){
        JsonResult forObject = restTemplate.getForObject(url, JsonResult.class, params);
        return forObject;
    }

    public  static JsonResult postWithParam(String url, Map params){
        HttpHeaders httpHeaders=new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        httpHeaders.set("token", (String) params.get("token"));
        params.remove("token");
        MultiValueMap<String,Object> values = new LinkedMultiValueMap<>();
        Iterator iterator = params.keySet().iterator();
        while (iterator.hasNext()){
            String next = (String) iterator.next();
            Object o = params.get(next);
            values.add(next,o);
        }
        HttpEntity httpEntity = new HttpEntity(values,httpHeaders);
        JsonResult jsonResult = restTemplate.postForObject(url,httpEntity, JsonResult.class);
        return jsonResult;
    }

    public  static JsonResult postWithBody(String url, Map params){
        HttpHeaders httpHeaders=new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        httpHeaders.set("token", (String) params.get("token"));
        params.remove("token");
        MultiValueMap<String,Object> values = new LinkedMultiValueMap<>();
        Iterator iterator = params.keySet().iterator();
        while (iterator.hasNext()){
            String next = (String) iterator.next();
            Object o = params.get(next);
            values.add(next,o);
        }
        HttpEntity httpEntity = new HttpEntity(values,httpHeaders);
        JsonResult jsonResult = restTemplate.postForObject(url,httpEntity, JsonResult.class);
        return jsonResult;
    }

}
